from . import db
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import Index, CheckConstraint, Numeric

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), nullable=False, unique=True)
    _password = db.Column(db.String(150), nullable=False)
    preferences = db.Column(db.Text)
    bookings = db.relationship('Booking', backref='user', lazy=True)

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    def check_password(self, password):
        return check_password_hash(self._password, password)

class Service(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text, nullable=False)
    price = db.Column(Numeric(10, 2), nullable=False)  # 使用Numeric类型存储货币值

class Booking(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
    service_id = db.Column(db.Integer, db.ForeignKey('service.id'), nullable=False, index=True)
    date = db.Column(db.DateTime, nullable=False)
    time = db.Column(db.Time, nullable=False)  # 使用Time类型存储时间
    nail_technician = db.Column(db.String(100), nullable=False)

class Payment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    booking_id = db.Column(db.Integer, db.ForeignKey('booking.id'), nullable=False, index=True)
    amount = db.Column(Numeric(10, 2), nullable=False)  # 使用Numeric类型存储货币值
    method = db.Column(db.String(50), nullable=False)
    status = db.Column(db.String(50), nullable=False)

class Review(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
    service_id = db.Column(db.Integer, db.ForeignKey('service.id'), nullable=False, index=True)
    rating = db.Column(db.Integer, CheckConstraint('rating >= 1 AND rating <= 5'), nullable=False)  # 添加数据完整性约束
    comment = db.Column(db.Text)